/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dtn.wsn.sunspot;

import com.dtn.wsn.dao.DataDAO;
import com.dtn.wsn.dao.SpotDAO;
import com.dtn.wsn.database.ConnectionPool;
import com.dtn.wsn.entity.Data;
import com.sun.spot.io.j2me.radiogram.RadiogramConnection;

import com.sun.spot.peripheral.TimeoutException;
import java.util.ArrayList;
import javax.microedition.io.Datagram;

/**
 * collect the data also filter the data, store data into database
 * @author hao
 */
public class DataCollector {
    //use SpotConnection and Database connection only.

    // Duration (in milliseconds) for which to collect samples.
    private int sampling_duration;
    private ConnectionPool connectionPool;

    public void setSampling_duration(int sampling_duration) {
        this.sampling_duration = sampling_duration;
    }

    public int getSampling_duration() {
        return sampling_duration;
    }
    //private RadiogramConnection rCon = null;
    //private WSNDBConnection DBC = new WSNDBConnection();
    //private static final String DATA_TABLE_NAME = "lightReadings";
    private RadiogramConnection rCon;

    public DataCollector(RadiogramConnection rCon, ConnectionPool dbPool) {
        this.sampling_duration = 60000;
        this.rCon = rCon;
        this.connectionPool = dbPool;
    }

    public int collectData() throws Exception {
        String mac_addr = null;
        String timestampe = null;
        int light_level = 0;
        double Temp = 0;
        double Batt = 0;
        int sampleCnt = 0;
        Datagram dg = null;
        long start = 0L;
	int spot_id = -1;
        ArrayList<Data> dataList = new ArrayList<Data>();

        System.out.println("Sampling for " + (this.sampling_duration)
                + " seconds ...\n[Each * indicates one sample, ! implies"
                + " radio timed out waiting for a sample]");
        start = System.currentTimeMillis();
        dg = rCon.newDatagram(rCon.getMaximumLength());

        // Main data collection loop
        while ((System.currentTimeMillis() - start) < this.sampling_duration) {
            try {
                // Read sensor sample received over the radio
                rCon.receive(dg);
                mac_addr = dg.readUTF();  // read sender's Id
                timestampe = dg.readUTF();  // read time stamp for the reading
                light_level = dg.readInt(); // read the sensor value
                Temp = dg.readDouble();
                Batt = dg.readDouble();
	
                //System.out.println("*  " +val + Batt + Temp);

                Data data = new Data();
                data.setLightLevel(light_level);
                data.setTimestample(timestampe);
                data.setTemperature(Temp);
                data.setBattery(Batt);
                dataList.add(data);

                if (sampleCnt == 0) {
                    //insert to the sunspotInfo table.
                    SpotDAO spotDao = new SpotDAO(this.connectionPool);
		    spot_id = spotDao.isExsist(mac_addr);
                    if (spot_id == -1) {
                        int isdone = spotDao.insertSpot(mac_addr);
                        if (isdone == 0) {
                            System.err.println("store sunspot mac_addr erro now");
                        }
                    }

                }
		data.setSpotId(spot_id);
                sampleCnt++;
                System.out.println("*  " + Batt + Temp);
                if (sampleCnt % 10 == 0) {
                    System.err.println("store now");
                    DataDAO dataDao = new DataDAO(this.connectionPool);
                    int isdone = dataDao.InsertData(dataList);
                    if (isdone == 1) {
                        dataList.clear();
                    }
                }


            } catch (TimeoutException e) {
                System.err.println("!");
            } catch (Exception e) {
                System.err.println("Caught " + e
                        + " while reading sensor samples.");
                throw e;
            }
        }
        if (dataList.size() != 0) {
            DataDAO dataDao = new DataDAO(this.connectionPool);
            int isdone = dataDao.InsertData(dataList);
            if (isdone == 0) {
                System.out.println("Erro in store data to DB");
            }
        }


        System.out.println("\nDone! Collected " + sampleCnt + " samples.");
        return sampleCnt;
    }
}
